package main

import (
	"context"
	"crypto/x509"
	"fmt"
	"log"
	"os"
	"protobuf-learn/proto"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func main() {
	// load tls from public CA
	//tlsCredentials := credentials.NewTLS(&tls.Config{})

	// load tls from privite CA
	certPool := x509.NewCertPool()
	cert, err := os.ReadFile("certs/ca.crt")
	if err != nil {
		log.Fatal(err)
	}
	if ok := certPool.AppendCertsFromPEM(cert); !ok {
		log.Fatal("failed to append CA cert")
	}
	tlsCredentials := credentials.NewClientTLSFromCert(certPool, "")

	// initialise a grpc connection
	host := ":50051"
	ctx := context.Background()
	conn, err := grpc.NewClient(
		host,
		//grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithTransportCredentials(tlsCredentials),
	)
	if err != nil {
		log.Fatal(err)
	}

	//create our client
	client := proto.NewStreamingServiceClient(conn)

	// initialize the client stream
	stream, err := client.LogStream(ctx)
	if err != nil {
		log.Fatal(err)
	}

	// send some log messages
	for i := range 5 {
		req := &proto.LogStreamRequest{
			Timestamp: timestamppb.New(time.Now()),
			Level:     proto.LogLevel_LOG_LEVEL_INFO,
			Message:   fmt.Sprintf("Hello log: %d", i),
		}

		if err := stream.Send(req); err != nil {
			log.Fatal(err)
		}
		time.Sleep(time.Second)
	}

	// close the steam
	res, err := stream.CloseAndRecv()
	if err != nil {
		log.Fatal(err)
	}

	// log the response from server
	log.Printf("number of send: %d", res.GetEntiesLogged())
}
